#*  @brief        路径管理

# 所有的配置都写在同一个地方。
# 配置内容为：
# ```
# nfs:$HOME/nfs
# ```

# 使用范例
# ```
# # 配置路径
# dir-path-set tmp  "/tmp"
# dir-path-set nfs  "\$HOME/nfs"
# # 打印路径
# dir-path-get nfs
# # 把文件拷贝到nfs路径下
# dir-path-do "cp -rf" nfs a.out
# ```

export DIR_CFG_PATH="${MYSC_CONFIG_ROOT}/dir.pathcfg"

# 执行命令到路径
# 判断输入的类型（支持数字与字符混用）
function dir-path-do () {
    if [ "$#" -lt 3 ]; then
        echo "need more args"
        echo '  e.g.  dir-path-do  "cp -rf"  nfs   a.out'
        return 1
    fi
    local _action="$1"
    local _path="$2"
    shift 2
    local args="$@"

    local relpath=""
    # 判断输入的类型（支持数字与字符混用）
    #echo $1| awk '{print($0~/^[-]?([0-9])+[.]?([0-9])+$/)?"number":"string"}'
    if [ -n "$(echo $_path| sed -n "/^[0-9]\+$/p")" ];then
        #echo "$line is number."
        relpath=`dir-path-get-by-index $_path`
    else
        #echo "$line is string."
        relpath=`dir-path-get $_path`
    fi

    if [ -z "$relpath" ]; then
        echo "path [$_path] not found."
        echo "try 'dir-path-set $_path somewhere' and do again."
		return 1
	fi
    local tmp=/tmp/.dir-path-do.$$.sh
    #echo "Exec [$_action $args $relpath]"
    echo -n "Exec [$_action"
    for arg in "$args" ;do
	    if [ -z "$arg" ];then
		    continue
	    fi
	    echo -n  " $arg"
    done
    echo " $relpath]"
    echo "$_action $args $relpath" > $tmp
    source $tmp
    rm $tmp -rf
}

# 配置路径
function dir-path-set () {
    local pathname="$1"
    local pathvalue="$2"
    if [ -z "$1" ]; then
    	return 1
	fi
    ## 如果 值为空，则代表删除
    if [ -z "$2" ]; then
		local oldt=`echo "^${pathname}:"| sed 's:\/:\\\/:g'`
		bash <<EOF
sed '/$oldt/d' -i $DIR_CFG_PATH
EOF
        echo "[D] $pathname"
		return
	fi

    ## 新增值或者修改值
    if [ ! -f "$DIR_CFG_PATH" ]; then
        mkdir -p `dirname $DIR_CFG_PATH`
        echo "$pathname:$pathvalue" >> $DIR_CFG_PATH
        bash <<EOF
        echo "[A] $pathname:$pathvalue"
EOF
		return 0
	fi

    # 如果使用到了'$'但不是'\$',那么需要告诉用户进行手动转义（因为在sed中会有bug）
    local escape_check=`echo "$pathvalue" | grep -F '$'`
    if [ ! -z "$escape_check" ];then
        #echo "$pathvalue" |  grep -F "\\$"
        #escape_check=`echo "$pathvalue" |  grep -F "\\$"| grep -F '\\'`
        escape_check=`echo "$pathvalue" |  grep -F "\\\\$"`
        if [ -z "$escape_check" ];then
            echo "To use '\$', please replace it as '\\\$'"
            return 1
        fi
    fi

    # 从 配置中查看是否有此行
    local result=`cat $DIR_CFG_PATH | grep $pathname | grep ":" | grep -v \#`
    if [ -z "$result" ]; then
        echo "$pathname:$pathvalue" >> $DIR_CFG_PATH
        bash <<EOF
        echo "[A] $pathname:$pathvalue"
EOF
    else
        bash <<EOF
        echo "[M] $pathname:$pathvalue"
EOF
        local _pathname=`echo "$pathname"   | sed 's:\/:\\\/:g'`
        local _pathvalue=`echo "$pathvalue" | sed 's:\/:\\\/:g'`
        local new_expr="${_pathname}:${_pathvalue}"
        bash <<EOF
sed -r -i "/^${_pathname}:*/c${new_expr}/" $DIR_CFG_PATH
EOF
	fi
}

# 获取路径
function dir-path-get () {
    local _path=$1
    if [ -z "$_path" ]; then
    	return 1
	fi
    if [ ! -f "$DIR_CFG_PATH" ]; then
        touch $DIR_CFG_PATH
		return 1
	fi
    ## 通过分析得到纯文本
    local result=`cat $DIR_CFG_PATH | grep -v "#"| grep -E "$_path:|^$_path:" -m 1 | awk -F: '{print$2}'`
    if [ -z "$result" ]; then
		return 0
	fi
    # 打印结果
    echo "$result"
    ## 转义(如果包括'$'等参数)
    #bash -c "echo $result"
}

# 获取路径（通过索引）
function dir-path-get-by-index () {
    local _index=$1
    if [ -z "$_index" ]; then
        return 1
    fi
    if [ ! -f "$DIR_CFG_PATH" ]; then
        touch $DIR_CFG_PATH
		return 1
	fi
    local max=`cat $DIR_CFG_PATH | wc -l`
    if [ $_index -gt $max ]; then
		return 1
    fi
    local _path=`cat $DIR_CFG_PATH | awk -F: '{print $1}' | sed -n "${_index}p"`
    dir-path-get ${_path}
}

# 跳转到路径 ，支持连续跳转
#
#   假设目前有下列目录
#   mkdir /tmp/t1 /tmp/t2
#
#   配置 路径
#   dir-path-set tmp /tmp
#   dir-path-set t1 t1
#   dir-path-set t2 t2
#
#   到达 /tmp/t1
#   to tmp t1
#
#   到达 /tmp/21
#   to tmp t2
function dir-path-to () {
    # 如果提供了参数，那么使用参数
    if [ $# -ne 0 ]; then
        until [ $# -eq 0 ]
        do
            dir-path-do 'cd' "$1" ""
            shift
        done
        return
    fi
    # 如果没有提供参数，那么询问
    ## 逐行解析并打印
    local i=0;
    #local max=0;
    cat $DIR_CFG_PATH | while read line
    do
        local context=`echo $line | awk -F: '{printf("%s\t%s\n",$1, $2)}'`
        #local cur_max_line=`echo $line | awk -F: '{printf("%s\t%s\n",$1, $2)}'| wc -c`
        i=$(($i+1)) # 自增
        echo "[$i] $context"
    done
    local max=$i
    ## 交互选择
    if [ $i -eq 0 ]; then
        echo "No item to pick."
        return 0
    fi
    echo "========================="
    echo ""
    echo "Which item(s) you want to pick? [1..$i]"
    echo " e.g : 1,2"
    read answer
        ## 获取 空格数
        #local space_c=`echo $answer |tr -cd ' '`
        #local loop_c=$(($space_c+1))
    echo $answer | tr ' '  '\n' | tr ','  '\n' | while read line
    do
        if [ -z "$line" ]; then
            continue
        fi
        dir-path-do 'cd' "${line}" ""
    done
}

function dir-path () {
    dir-path-to "$@"
}
function to () {
    dir-path-to "$@"
}
alias t=to

#### 常见的行动 ####
# 复制文件到path
function dir-path-do-copy () {
    #local _path=$1
    #shift
    #local args="$@"
    dir-path-do 'cp -rfv' "$@"
}
function cp-to () {
    dir-path-do-copy "$@"
}
# 移动文件到path
function dir-path-do-move () {
    #local _path=$1
    #shift
    #local args="$@"
    dir-path-do 'mv -vf' "$@"
}
function mv-to () {
    dir-path-do-move "$@"
}
